import Joi from "joi";
import { ResultSetHeader } from "mysql2";
import { getDB } from "~/server/utils/db/mysql/index";
import {
  getLoginUid,
  responseJson,
  genTitle,
} from "~/server/utils/helper/index";
/**
 * 1、判断用户是否登录
 * 2、已登录创建文章
 */

export default defineEventHandler(async (event) => {
  // 1、判断用户是否登录
  let uid = getLoginUid(event);
  if (uid === 0) {
    setResponseStatus(event, 401);
    return responseJson(1, "请登录", {});
  }

  // 获取客户端传来的手机号和密码
  const body = await readBody(event);

  // 数据校验
  const schema = Joi.object({
    notebookId: Joi.number().required(),
  });
  try {
    await schema.validateAsync(body);
  } catch (error) {
    return responseJson(1, "参数错误", {});
  }

  const con = getDB();

  try {
    const [rows] = await con.execute<ResultSetHeader>(
      "INSERT INTO `notes` (`title`,`content_md`,`state`,`uid`) value (?,?,?,?)",
      [genTitle(), "", 1, uid]
    );
    //   关联文集
    if (rows.affectedRows !== 0) {
      const insertId = rows.insertId;
      const [rows2] = await con.execute<ResultSetHeader>(
        "INSERT INTO `notebook_notes` (`notebook_id`,`note_id`) value (?,?)",
        [body.notebookId, insertId]
      );
      if (rows2.affectedRows !== 0) {
        return responseJson(0, "创建成功", {
          noteId: insertId,
        });
      } else {
        return responseJson(1, "文章创建成功，但关联文集失败", {});
      }
    } else {
      return responseJson(1, "文章创建失败", {});
    }
  } catch (error) {
    // 记录错误详情以便调试
    console.error("创建文章失败错误详情:", error);
    if (error instanceof Error) {
      console.error("错误消息:", error.message);
      console.error("错误堆栈:", error.stack);
    }
    return responseJson(1, "创建失败", {});
  }
  // 注意：不要关闭连接池！连接池应该保持打开状态以供后续使用
  // 连接池会自动管理连接的获取和释放
});
